#include <QNetworkProxy>
#include "TcpNetwork.h"
#include <iostream>
TcpNetwork::TcpNetwork()
    : NetworkInterface()
    , currentReceiveBufferIndex(0)
{
    //这里需要连接信号，因此需要将其作为元对象系统的
    QObject::connect(&tcpSocket, &QTcpSocket::readyRead, this, &TcpNetwork::onReadyRead);
    QObject::connect(&tcpSocket, &QTcpSocket::connected, this, &TcpNetwork::onConnected);
    QObject::connect(&tcpSocket, &QTcpSocket::errorOccurred, this, &TcpNetwork::onError);
    tcpSocket.setProxy(QNetworkProxy::NoProxy);
    receiveBuffers[0].resize(expectedPacketSize);
    receiveBuffers[1].resize(expectedPacketSize);
}

void TcpNetwork::connect(const QString &hostAddress, const quint64 &hostPort)
{
    tcpSocket.connectToHost(hostAddress, hostPort);
    if (tcpSocket.waitForConnected(100)) { // 等待1秒钟连接
        qDebug() << "Connected!";
    } else {
        qDebug() << "Connection failed!";
    }
}

void TcpNetwork::sendData(const QByteArray &data)
{
    qint64 sendBytes = tcpSocket.write(data);
    if (sendBytes <= 0) {
        std::cerr << "Failed to send data!" << std::endl;
    }
    // qDebug() << data;
    std::cerr << "sendBytes: " << sendBytes << std::endl;
}

QByteArray TcpNetwork::readData(qint64 readBytes)
{
    // QByteArray tmp = transBuffer;
    // transBuffer.clear();
    QByteArray rawData = receiveBuffers[currentReceiveBufferIndex].left(readBytes);
    receiveBuffers[currentReceiveBufferIndex].clear();
    receiveBuffers[currentReceiveBufferIndex].resize(expectedPacketSize);
    return rawData;
}

void TcpNetwork::disconnect()
{
    tcpSocket.disconnectFromHost();
}

QAbstractSocket::SocketState TcpNetwork::socketStatus()
{
    return tcpSocket.state();
}

void TcpNetwork::onReadyRead()
{
    while (tcpSocket.bytesAvailable()) {
        // qDebug() << "接收";

        //获取当前索引的缓冲区
        QByteArray *currentReceiveBuffer = &receiveBuffers[currentReceiveBufferIndex];
        if (!currentReceiveBuffer) {
            std::cerr << "currentReceiveBuffer is nullptr" << std::endl;
            return;
        }
        if (!currentReceiveBuffer->isEmpty()) {
            //切换缓冲区
            currentReceiveBufferIndex = (currentReceiveBufferIndex + 1) % 2; // 切换到下一个缓冲区
            currentReceiveBuffer = &receiveBuffers[currentReceiveBufferIndex];
        }

        if (!currentReceiveBuffer->data()) {
            std::cerr << "currentReceiveBuffer data is nullptr" << std::endl;
        }
        qint64 readBytes = tcpSocket.read((*currentReceiveBuffer).data(), expectedPacketSize);

        if (readBytes > 0) {
            emit dataArrival(readBytes);
        }

        break;
    }
}

void TcpNetwork::onConnected()
{
    qDebug() << "Successfully connected to the TcpServer!";
}

void TcpNetwork::onError(QAbstractSocket::SocketError socketError)
{
    // qDebug() << "Connection failed with error:" << socketError;
    if (socketError == QAbstractSocket::RemoteHostClosedError) {
        tcpSocket.disconnectFromHost();
        qDebug() << "TCP connection closed";
    }
}

void TcpNetwork::onDisconnected()
{
    qDebug() << "The TCP server has been disconnected successfully!";
}
